package com.bbzn.device.client.config;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import java.util.ArrayList;
import java.util.List;


/**
 * @Author wulongbo
 * @Date 2022/1/19 15:17
 * @Version 1.0
 * @description 配置mongoDB的属性
 */

@Configuration
@Slf4j
public class MongoAutoConfiguration {

    @Value("${mongodb.hostports}")
    private String hostports;
    @Value("${mongodb.maxConnect}")
    private String maxConnect;
    @Value("${mongodb.maxWaitThread}")
    private String maxWaitThread;
    @Value("${mongodb.maxTimeOut}")
    private String maxTimeOut;
    @Value("${mongodb.maxWaitTime}")
    private String maxWaitTime;
    @Value("${mongodb.username}")
    private String username;
    @Value("${mongodb.password}")
    private String password;
    @Value("${mongodb.database}")
    private String database;
    @Value("${mongodb.collection")
    private String collection;

    /**
     * 功能描述: 根据自己创建的工厂初始化一个template
     *
     * @param
     * @return:org.springframework.data.mongodb.core.MongoTemplate
     * @since: v1.0
     */
    @Bean
    @Primary
    public MongoTemplate template() {
        return new MongoTemplate(factory());
    }

    /**
     * 功能描述: 创建数据库名称对应的工厂，数据库名称可以通过配置文件导入
     *
     * @param
     * @return:org.springframework.data.mongodb.MongoDbFactory
     * @since: v1.0
     */
    @Bean("mongoDbFactory")
    public MongoDbFactory factory() {
        return new SimpleMongoDbFactory(client(), "baba_icloud");
    }

    /**
     * 功能描述: 配置client，client中传入的ip和端口可以通过配置文件读入
     *
     * @param
     * @return:com.mongodb.MongoClient
     * @since: v1.0
     */
    @Bean("mongoClient")
    public MongoClient client() {
        MongoClient mongoClient = null;
        MongoClientOptions.Builder build = new MongoClientOptions.Builder();
        build.connectionsPerHost(Integer.valueOf(maxConnect));
        build.threadsAllowedToBlockForConnectionMultiplier(Integer.valueOf(maxWaitThread));
        build.connectTimeout(Integer.valueOf(maxTimeOut) * 1000);
        build.maxWaitTime(Integer.valueOf(maxWaitTime) * 1000);
        MongoClientOptions options = build.build();
        try {
            List<ServerAddress> addrs = new ArrayList<ServerAddress>();
            for (String hostport : hostports.split(", *")) {
                if (StringUtils.isBlank(hostport)) {
                    continue;
                }
                hostport = hostport.trim();

                ServerAddress serverAddress = new ServerAddress(hostport.split(":")[0],Integer.valueOf(hostport.split(":")[1]));
                addrs.add(serverAddress);
            }

            MongoCredential credential = MongoCredential.createScramSha1Credential(username, database, password.toCharArray());
            List<MongoCredential> credentials = new ArrayList<MongoCredential>();
            credentials.add(credential);
            mongoClient = new MongoClient(addrs,credentials, options);

            log.info("【mongodb client】: mongodb客户端创建成功");
        } catch (Exception e) {
            log.error("【mongodb client】: mongodb客户端创建成功");
            e.printStackTrace();
        }
        return mongoClient;
    }

}
